package com.hxd.service;

import java.util.Date;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.hxd.common.constant.Constants;
import com.hxd.common.exception.DataException;
import com.hxd.common.utils.RedisUtils;
import com.hxd.pojo.TokenVO;

import cn.hutool.core.util.IdUtil;

@Service
public class TokenService {
	
	@Value("${token.expire}")
	private long expire;

	@Autowired
	private RedisUtils redisUtils;
	
	public TokenVO createToken(Integer userId) {
		TokenVO tokenVO = new TokenVO();
		tokenVO.setId(userId);
		
		String token = IdUtil.simpleUUID();
		tokenVO.setToken(token);
		// 当前时间
		Date now = new Date();
		// 过期时间
		Date expireTime = new Date(now.getTime() + expire);
		tokenVO.setExpireTime(expireTime.getTime());
		
		redisUtils.set(Constants.REDIS_USER_PRE + token + ":" + userId, tokenVO, expire/1000);
		return tokenVO;
	}
	
	public void removeByToken(String token) {
		Set<String> keys = redisUtils.keys(Constants.REDIS_USER_PRE + token + ":*");
		if(keys.size() == 0) {
			return ;
		}
		String[] keysArr = keys.toArray(new String[0]);
		redisUtils.del(keysArr);
	}
	
	public void removeTokenByUserId(Integer userId) {
		Set<String> keys = redisUtils.keys(Constants.REDIS_USER_PRE + "*:" + userId);
		if(keys.size() == 0) {
			return ;
		}
		String[] keysArr=keys.toArray(new String[0]);
		redisUtils.del(keysArr);
	}
	
	public TokenVO getToken(String token) {
		Set<String> keys = redisUtils.keys(Constants.REDIS_USER_PRE + token + ":*");
		if(keys.size() == 0) {
			return null;
		}
		if(keys.size() > 1) {
			throw new DataException("存在多个令牌");
		}
		String redisKey = null;
		for (String string : keys) {
			redisKey = string;
		}
		return (TokenVO) redisUtils.get(redisKey);
	}
	
}
